#include "stm32f10x.h"                  // Device header
#include "Delay.h"

int16_t Encoder_Count;

void Encoder_Init(void)
 {
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB,ENABLE);//启用RCC时钟
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO,ENABLE);//启用RCC时钟
	//EXTI和NVIC（内核外设）两个外设的时钟一直打开，不需要我们开启时钟

	/*配置GPIOB引脚*/
	GPIO_InitTypeDef GPIO_InitStructure;//定义GPIO结构体
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;//上拉输入
	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0 | GPIO_Pin_1;
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_Init(GPIOB,&GPIO_InitStructure);
	
	/*配置AFIO外部中断引脚选择*/
	 //将AFIO多路选择器开关拨向PB1 | PB0;
	GPIO_EXTILineConfig(GPIO_PortSourceGPIOB,GPIO_PinSource0);
	GPIO_EXTILineConfig(GPIO_PortSourceGPIOB,GPIO_PinSource1);
	EXTI_InitTypeDef EXTI_InitStructure;//定义EXTI结构体
	/*指定中断线*/ 
	EXTI_InitStructure.EXTI_Line = EXTI_Line0 | EXTI_Line1;
	EXTI_InitStructure.EXTI_LineCmd = ENABLE;//使能
	EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt;//设置为中断模式
	EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Falling;//Rising上升沿触发，Falling下降沿触发
	EXTI_Init(&EXTI_InitStructure);
	
	/*配置NVIC*/
	//分组方式整个芯片只能用1种
	NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);//抢占优先级和响应优先级分组方式
	
	NVIC_InitTypeDef NVIC_InitStructure;//定义NVIC结构体
	NVIC_InitStructure.NVIC_IRQChannel = EXTI0_IRQn;//指定通道
	NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;//中断通道使能
	NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 1;//给抢占优先级设置为1
	NVIC_InitStructure.NVIC_IRQChannelSubPriority = 1;//响应优先级也设置为1
	NVIC_Init(&NVIC_InitStructure);
	
	NVIC_InitStructure.NVIC_IRQChannel = EXTI1_IRQn;//指定通道
	NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;//中断通道使能
	NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 1;//给抢占优先级设置为1
	NVIC_InitStructure.NVIC_IRQChannelSubPriority = 2;//响应优先级也设置为1
	NVIC_Init(&NVIC_InitStructure);
 }
int16_t Encoder_Get(void)
{
	int16_t Temp;
	Temp = Encoder_Count;
	Encoder_Count = 0;
	return Temp;
}

void EXTI0_IRQHandler(void)
{
	//先进行一个中断标志位的判断
	if(EXTI_GetITStatus(EXTI_Line0) == SET)//启用中断
	{
		if(GPIO_ReadInputDataBit(GPIOB,GPIO_Pin_1) == 0)//如果是，那么是反转
		{
			Encoder_Count --;
		}
		//调用一下清除中断标志位的函数
		EXTI_ClearITPendingBit(EXTI_Line0);
	}
}
 
void EXTI1_IRQHandler(void)
{
	//先进行一个中断标志位的判断
	if(EXTI_GetITStatus(EXTI_Line1) == SET)//启用中断
	{
		if(GPIO_ReadInputDataBit(GPIOB,GPIO_Pin_0) == 0)//如果是，那么是正转
		{
			Encoder_Count ++;
		}
		//调用一下清除中断标志位的函数
		EXTI_ClearITPendingBit(EXTI_Line1);
	}
}
